import style from './style.module.less'
import { Button, Form, Input, message } from 'antd'
import UploadImg from '../Upload'
import React, { ChangeEvent, useState } from 'react'
import * as api from '../../services/api'
import { useHistory } from 'react-router-dom'

export default function UpdateUserInfo(props: any) {
  let token: string = props.token

  const limit: number = 10

  const [imgKey, setImgKey] = useState<string>('')
  const [nickname, setNickname] = useState<string>('')

  const history = useHistory()

  function getImgKey(key: string) {
    setImgKey(key)
  }

  async function updateUserInfo() {
    try {
      let res = await api.updateUserInfo(token, imgKey, nickname)
      if (res.data.stat === 'ok') {
        history.push(`/personal/${token}`)
      } else {
        message.destroy()
        message.error(res.data.msg)
      }
    } catch (e) {
      throw e
    }
  }

  function setNickNameOnchange(e: ChangeEvent<HTMLInputElement>) {
    if (e.target.value.length <= limit) {
      setNickname(e.target.value)
    } else {
      setNickname(e.target.value.slice(0, limit))
      message.destroy()
      message.error(`昵称长度不能超过${limit}个字符`)
    }
  }

  return (
    <div className={style.formLeft}>
      <p className={style.formTitle}>修改用户信息</p>
      <Form.Item>
        昵&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;称:
        <Input
          className={style.formNickname}
          value={nickname}
          onChange={(event) => setNickNameOnchange(event)}
        />
      </Form.Item>
      <Form.Item>
        <div className={style.formAvatar}>
          <span className={style.formAvatarTitle}>头像上传:</span>
          <p className={style.formAvatarSpace}>&nbsp;</p>
          <UploadImg getImgKey={(key: string) => getImgKey(key)} />
        </div>
      </Form.Item>
      <Form.Item>
        <Button type="primary" onClick={updateUserInfo}>
          修改用户信息
        </Button>
      </Form.Item>
    </div>
  )
}
